# -*- coding: utf-8 -*

__author__ = 'huangxiaoli'

'''
    监控服务器状态 实时读取
    监控指标：
        host
        time
        load avg
        memTotal
        memUsage
        memFree
    API请求地址:
    http://192.168.1.201/stat/list
'''
from flask import Flask
import socket
import time
import json
import logging
from conf import config,config_flask,config_flask_override

app = Flask(__name__)
logger = logging.getLogger('mylogger')
formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
fh = logging.FileHandler('logging_flask.log')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.setLevel(logging.INFO)

class mon:

    def getTime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

    def getHost(self):
        return socket.gethostname()

    def getLoadAvg(self):
        with open('/proc/loadavg') as load_open:
            a = load_open.read().split()[:3]
            return ','.join(a)

    def getMem(self):
        with open('/proc/meminfo') as mem_open:
            T = int(mem_open.readline().split()[1])
            F = int(mem_open.readline().split()[1])
            A = int(mem_open.readline().split()[1])
            B = int(mem_open.readline().split()[1])
            C = int(mem_open.readline().split()[1])
            return (T,F,A,B,C)

@app.route('/api/list/',methods=['GET','POST'])
def monList():
    m = mon()
    moniDt = {
        "host":m.getHost(),
        'time':m.getTime(),
        'load_avg':m.getLoadAvg(),
        'mem_total':m.getMem()[0],
        'mem_free': m.getMem()[1],
        'mem_available': m.getMem()[2],
        'mem_buffers': m.getMem()[3],
        'mem_cached': m.getMem()[4]
    }
    return json.dumps(moniDt)

if __name__ == '__main__':
    logger.info('**服务器监控程序启动**')
    configs = config_flask.configs
    try:
        configs = config.merge(configs, config_flask_override.configs)
    except ImportError:
        # 日志记录
        logger.info('**import模块报错，请检测配置文件**')
        pass
    host = configs['flask']['host']
    port = configs['flask']['port']
    debug = configs['flask']['debug']
    app.run(host=host,port=port,debug=debug)